package com.luych.cloud.database.comparetor.mysql;

import com.luych.cloud.database.comparetor.core.Column;
import com.luych.cloud.database.comparetor.core.Database;
import com.luych.cloud.database.comparetor.core.Table;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.StringJoiner;

public class MysqlDatabase implements Database {

    private String name;
    private List<Table> tables;

    public MysqlDatabase() {
    }

    public MysqlDatabase(String name, List<Table> tables) {
        this.name = name;
        this.tables = tables;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setTables(List<Table> tables) {
        this.tables = tables;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public List<Table> getTables() {
        return tables;
    }

    @Override
    public String getCreateTableSql(Table table) {
        String sql = "CREATE TABLE " + table.getName().toLowerCase() + "(";
        StringJoiner joiner = new StringJoiner(",<br/>", "<br/>", "<br/>");
        for (Column column : table.getColumns()) {
            String joinerSql = "&nbsp;&nbsp;&nbsp;&nbsp;" + column.getName().toLowerCase() + " " + column.getColumnType();
            if (!column.isNullable()) {
                joinerSql += " NOT NULL";
            }
            if (!StringUtils.isEmpty(column.getComment())) {
                joinerSql += " COMMENT '" + column.getComment() + "'";
            }
            joiner.add(joinerSql);
        }
        sql += joiner.toString() + ")";
        if (!StringUtils.isEmpty(table.getComment())) {
            sql += " COMMENT '" + table.getComment() + "'";
        }
        sql += ";";
        if (!CollectionUtils.isEmpty(table.getPrimaryKey())) {
            sql +=  "<br/>" +
                    "ALTER TABLE " + table.getName().toLowerCase() +" " +
                    "ADD CONSTRAINT " + table.getName().toLowerCase() + "_pk " +
                    "PRIMARY KEY (" + String.join(",", table.getPrimaryKey()) + ");";
        }
        return sql;
    }

    @Override
    public String getRemoveTableSql(String tableName) {
        return "DROP TABLE " + tableName.toLowerCase() + ";";
    }
}
